//package com.gopay.bis.server;
//
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.net.InetAddress;
//import java.net.Socket;
//import java.util.Date;
//import java.util.List;
//import java.util.Map;
//
//import javax.servlet.ServletContext;
//
//import org.apache.commons.lang.builder.ReflectionToStringBuilder;
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
//import org.springframework.context.ApplicationContext;
//import org.springframework.web.context.support.WebApplicationContextUtils;
//
//import com.gopay.common.constants.cbrmb.CbRmbBankConstants;
//import com.gopay.common.constants.cbrmb.CbRmbBankOrderState;
//import com.gopay.common.constants.cbrmb.CbRmbOrderState;
//import com.gopay.common.cps.dao.cbrmb.CbRmbBankMessageDtlDao;
//import com.gopay.common.cps.dao.cbrmb.CbRmbBankOrderDtlDao;
//import com.gopay.common.cps.dao.cbrmb.CbRmbBankOrderMessageRelDao;
//import com.gopay.common.cps.dao.cbrmb.CbRmbTranAssistDtlDao;
//import com.gopay.common.cps.dao.cbrmb.CbRmbTranAssistDtlLogDao;
//import com.gopay.common.domain.bank.ccb.cbrmb.CbRmbXmlFile;
//import com.gopay.common.domain.bank.ccb.cbrmb.CbRmbXmlFileHead;
//import com.gopay.common.domain.bank.ccb.cbrmb.req.CbRmbNotificationMsg;
//import com.gopay.common.domain.bank.ccb.cbrmb.res.CbRmbResponseMsg;
//import com.gopay.common.domain.cbrmb.CbRmbBankMessageDtl;
//import com.gopay.common.domain.cbrmb.CbRmbBankOrderDtl;
//import com.gopay.common.domain.cbrmb.CbRmbBankOrderMessageRel;
//import com.gopay.common.domain.cbrmb.CbRmbTranAssistDtl;
//import com.gopay.common.domain.cbrmb.CbRmbTranAssistDtlLog;
//import com.gopay.common.util.cbrmb.BeanMapper;
//import com.gopay.common.util.cbrmb.FileUtils;
//import com.gopay.common.util.cbrmb.FtpUtils;
//import com.gopay.remote.cps.cbrmb.CbrmbBankCallbackRemoteService;
//
///**
// * 
// * @ClassName: CbRmbProcessSocketData
// * @Description: 客户端数据处理
// * @author gd.cui
// * @date 2016年7月11日 上午11:45:50 ww.gopay.com.cn Inc.All rights reserved.
// */
//public class CbRmbProcessSocketData extends Thread {
//
//	private CbRmbBankOrderDtlDao cbRmbBankOrderDtlDao;
//
//	private CbRmbBankOrderMessageRelDao cbRmbBankOrderMessageRelDao;
//
//	private CbRmbBankMessageDtlDao cbRmbBankMessageDtlDao;
//
//	private CbRmbTranAssistDtlDao cbRmbTranAssistDtlDao;
//
//	private CbrmbBankCallbackRemoteService cbrmbBankCallbackClient;
//
//	private CbRmbTranAssistDtlLogDao cbRmbTranAssistDtlLogDao;
//
//	private static Log logger = LogFactory.getLog(CbRmbProcessSocketData.class);
//
//	private Socket socket;
//
//	private ServletContext servletContext;
//
//	private Map<String, String> cbrConfig;
//
//	@SuppressWarnings("unchecked")
//	public void init() {
//		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
//		cbRmbBankOrderDtlDao = (CbRmbBankOrderDtlDao) context.getBean("cbRmbBankOrderDtlDao");
//		cbRmbBankOrderMessageRelDao = (CbRmbBankOrderMessageRelDao) context.getBean("cbRmbBankOrderMessageRelDao");
//		cbRmbBankMessageDtlDao = (CbRmbBankMessageDtlDao) context.getBean("cbRmbBankMessageDtlDao");
//		cbRmbTranAssistDtlDao = (CbRmbTranAssistDtlDao) context.getBean("cbRmbTranAssistDtlDao");
//		cbrmbBankCallbackClient = (CbrmbBankCallbackRemoteService) context.getBean("cbrmbBankCallbackClient");
//		cbrConfig = (Map<String, String>) context.getBean("cbrConfig");
//		cbRmbTranAssistDtlLogDao = (CbRmbTranAssistDtlLogDao) context.getBean("cbRmbTranAssistDtlLogDao");
//	}
//
//	public CbRmbProcessSocketData() {
//		super();
//	}
//
//	public CbRmbProcessSocketData(Socket socket, ServletContext servletContext) {
//		this.socket = socket;
//		this.servletContext = servletContext;
//		init();
//	}
//
//	@Override
//	public void run() {
//		logger.error("******* cbrmb socket server start CbRmbProcessSocketData ");
//		InetAddress remoteAddress = socket.getInetAddress();
//		String remoteIp = remoteAddress.getHostAddress();
//		logger.error("remote ip :" + remoteIp);
//		/*
//		 * if (!CbRmbBankConstants.PERMIT_IP.equalsIgnoreCase(remoteIp)) {
//		 * logger.debug("接受信息时IP不合法"); }
//		 */
//		OutputStream os = null;
//		InputStream is = null;
//		CbRmbBankMessageDtl cbRmbBankMessageDtl = new CbRmbBankMessageDtl();
//		try {
//			os = socket.getOutputStream();
//			is = socket.getInputStream();
//			logger.debug("*****回盘-接受socket数据流信息");
//			byte[] source = FileUtils.toByteArray(is);
//			logger.debug("*****回盘-接受socket数据流信息" + source.length);
//			CbRmbNotificationMsg notificationMsg = new CbRmbNotificationMsg(source);
//			logger.error("*****回盘-接受到socket信息:" + ReflectionToStringBuilder.toString(notificationMsg));
//			CbRmbResponseMsg responseMsg = checkFile(source, notificationMsg);
//			logger.error("*****回盘-返回数据信息:" + ReflectionToStringBuilder.toString(responseMsg));
//			os.write(responseMsg.getByteData());
//			os.flush();
//			BeanMapper.copy(notificationMsg, cbRmbBankMessageDtl);
//			cbRmbBankMessageDtl.setRetCode(responseMsg.getRetCode());
//			cbRmbBankMessageDtl.setRetMsg(responseMsg.getRetMsg());
//			cbRmbBankMessageDtl.setCreateTime(new Date());
//			cbRmbBankMessageDtl.setLastUpdateTime(new Date());
//			cbRmbBankMessageDtlDao.save(cbRmbBankMessageDtl);
//            //回盘信息日志先不做单独处理
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			if (os != null) {
//				try {
//					os.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//			if (is != null) {
//				try {
//					is.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//			if (null != socket) {
//				logger.info(" *********release connect socket");
//				try {
//					socket.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
//		try {
//			/**
//			 * 此处可能会有问题：如果回盘信息接收成功，在读取或更新以下文件时有部分失败，可能会造成数据无法完全解析。
//			 * 现想到修改方法：算了先不写了， 还是记下吧 ，在通知里增加表示
//			 */
//			String resXml = xmlFileToString(cbRmbBankMessageDtl.getFileName().trim());
//			CbRmbXmlFile xmlFile = BeanMapper.toBean(resXml.replace(CbRmbBankConstants.XML_HEAD, ""),
//					CbRmbXmlFile.class);
//			List<CbRmbBankOrderDtl> cbRmbBankOrderDtls = BeanMapper.mapList(xmlFile.getCbRmbXmlFileBody(),
//					CbRmbBankOrderDtl.class);
//			int orderMessageId = 0;
//			for (CbRmbBankOrderDtl order : cbRmbBankOrderDtls) {
//				logger.error("*********回盘数据:xml文件数据_1：" + ReflectionToStringBuilder.toString(order));
//				CbRmbBankOrderDtl orderDtl = cbRmbBankOrderDtlDao.findByGopayOrderId(order.getGopayOrderId());
//				logger.error("*********回盘数据:local数据_1：" + orderDtl.getGopayOrderId());
//				if (orderMessageId == 0) {
//					orderMessageId = orderDtl.getOrderMessageId();
//				}
//				orderDtl.setFims_no(order.getFims_no());
//				orderDtl.setBank_bus_no(order.getBank_bus_no());
//				orderDtl.setBank_exchangerate(order.getBank_exchangerate());
//				orderDtl.setBank_handling(order.getBank_handling());
//				orderDtl.setBank_payamt(order.getBank_payamt());
//				orderDtl.setBank_telegram(order.getBank_telegram());
//				orderDtl.setReport_date(order.getReport_date());
//				orderDtl.setReturn_code(order.getReturn_code());
//				orderDtl.setReturn_info(order.getReturn_info());
//				orderDtl.setRcpm_no(order.getRcpm_no());
//				orderDtl.setState(CbRmbBankOrderState._03.value);
//				orderDtl.setLastUpdateTime(new Date());
//				cbRmbBankOrderDtlDao.update(orderDtl);
//				CbRmbTranAssistDtl tranAssisDtl = cbRmbTranAssistDtlDao.findByGopayOrderId(order.getGopayOrderId());
//				if (CbRmbBankConstants.PAY_SUCCESS.equals(orderDtl.getReturn_code())) {
//					// 支付成功
//					tranAssisDtl.setState(CbRmbOrderState.PAY_SUCCESS.value);
//				} else {
//					// 支付失败
//					tranAssisDtl.setState(CbRmbOrderState.PAY_FAIL.value);
//					CbRmbTranAssistDtlLog assistLog = new CbRmbTranAssistDtlLog();
//					assistLog.setCreateTime(new Date());
//					assistLog.setLastUpdateTime(new Date());
//					assistLog.setGopayOrderId(order.getGopayOrderId());
//					assistLog.setReturnCode(order.getReturn_code());
//					assistLog.setReturnInfo(order.getReturn_info());
//					assistLog.setTranType("2");// 0报盘,1回盘,2付款
//					cbRmbTranAssistDtlLogDao.save(assistLog);
//				}
//				tranAssisDtl.setHpFinishTime(new Date());
//				tranAssisDtl.setLastUpdateTime(new Date());
//				cbRmbTranAssistDtlDao.update(tranAssisDtl);
//			}
//			cbRmbBankMessageDtl.setOrderMessageId(orderMessageId);
//			cbRmbBankMessageDtl.setLastUpdateTime(new Date());
//			cbRmbBankMessageDtlDao.update(cbRmbBankMessageDtl);
//			logger.error("*****update orderMessageId=" + orderMessageId + ",CbRmbBankMessageDtl="
//					+ cbRmbBankMessageDtl.getMessageId());
//			CbRmbBankOrderMessageRel orderMessageRel = cbRmbBankOrderMessageRelDao.find(CbRmbBankOrderMessageRel.class,
//					orderMessageId);
//			logger.error("****" + ReflectionToStringBuilder.toString(orderMessageRel));
//			CbRmbXmlFileHead xmlHead = xmlFile.getCbRmbXmlFileHead();
//			orderMessageRel.setTotalpayamt(xmlHead.getTotalpayamt());
//			orderMessageRel.setTotalhandling(xmlHead.getTotalhandling());
//			orderMessageRel.setTotaltelegram(xmlHead.getTotaltelegram());
//			orderMessageRel.setResXml(resXml);
//			orderMessageRel.setLastUpdateTime(new Date());
//			cbRmbBankOrderMessageRelDao.update(orderMessageRel);
//			// 此处会调用cps做账，所以放在最后，防止cps出错后导致其他数据不全;
//			for (CbRmbBankOrderDtl order : cbRmbBankOrderDtls) {
//				logger.error(" cps 开始做账*****");
//				CbRmbBankOrderDtl orderDtl = cbRmbBankOrderDtlDao.findByGopayOrderId(order.getGopayOrderId());
//				if (CbRmbBankConstants.PAY_SUCCESS.equals(orderDtl.getReturn_code())) {
//					// 支付成功
//					cbrmbBankCallbackClient.bankReturnFinishOrder(orderDtl);
//					logger.error(" cps 做账完成");
//				}
//
//			}
//			xmlFileDownlocal(cbRmbBankMessageDtl.getFileName().trim());
//		} catch (Exception e) {
//			logger.info("*********文件处理异常" + e);
//		}
//	}
//
//	/**
//	 * 
//	 * @Description: ftp文件下载到本地
//	 * @param fileName
//	 * @return
//	 * @throws Exception
//	 * @author
//	 */
//	private boolean xmlFileDownlocal(String fileName) throws Exception {
//		FtpUtils ftp = new FtpUtils(cbrConfig.get("ftp.ip"), Integer.valueOf(cbrConfig.get("ftp.port")),
//				cbrConfig.get("ftp.username"), cbrConfig.get("ftp.password"), cbrConfig.get("ftp.download.path"));
//
//		String localFileName = cbrConfig.get("local.download.path") + fileName;
//		logger.error("**** 下载文件名称：*****　" + fileName);
//		return ftp.downFile(fileName, localFileName, CbRmbBankConstants.CHARSET_GBK);
//	}
//
//	/**
//	 * 
//	 * @Description: xml文件转换为string字符串
//	 * @param fileName
//	 * @return
//	 * @throws Exception
//	 * @author gd.cui
//	 */
//	private String xmlFileToString(String fileName) throws Exception {
//		FtpUtils ftp = new FtpUtils(cbrConfig.get("ftp.ip"), Integer.valueOf(cbrConfig.get("ftp.port")),
//				cbrConfig.get("ftp.username"), cbrConfig.get("ftp.password"), cbrConfig.get("ftp.download.path"));
//		String localFileName = cbrConfig.get("local.download.path") + fileName;
//		logger.error("**** ccb send file name*****　" + fileName);
//		return ftp.readFile(fileName, localFileName, CbRmbBankConstants.CHARSET_GBK);
//	}
//
//	/**
//	 * 
//	 * @Description: 文件校验，并返回信息
//	 * @param source
//	 * @param notificationMsg
//	 * @return
//	 * @author gd.cui
//	 */
//	private CbRmbResponseMsg checkFile(byte[] source, CbRmbNotificationMsg notificationMsg) {
//		CbRmbResponseMsg responseMsg = BeanMapper.map(notificationMsg, CbRmbResponseMsg.class);
//		if (source != null && source.length >= CbRmbNotificationMsg.MSG_NOTIFICATION_LENGTH) {
//			responseMsg.setRetCode(CbRmbBankConstants.SUCCESS);
//			responseMsg.setRetMsg("请求接收成功");
//		} else {
//			responseMsg.setRetCode("900004");
//			responseMsg.setRetMsg("HTTP请求错误，报文not enough");
//		}
//		return responseMsg;
//	}
//
//	public Map<String, String> getCbrConfig() {
//		return cbrConfig;
//	}
//
//	public void setCbrConfig(Map<String, String> cbrConfig) {
//		this.cbrConfig = cbrConfig;
//	}
//
//}
